package cn.wp.common.core.plugin.verification;

import cn.hutool.core.util.StrUtil;
import cn.wp.common.core.model.WpState;
import cn.wp.common.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 验证码服务类
 * Created by chenyb on 2019/10/18
 */
@Service
public class VerificationCodeService {

    @Autowired
    private VerificationCodeDao verificationCodeDao;

    /**
     * 保存验证码
     * @return
     */
    public String saveCode(String randomStr,String code){
        verificationCodeDao.insertCode(randomStr,code);
        return code;
    }

   /* *//**
     * 生成验证码
     * @return
     *//*
   public String genCode(String randomStr){
       String code = RandomUtil.randomNumber(4);
       verificationCodeDao.saveCode(randomStr,code);
       return code;
   }*/

    /**
     * 生成验证码,指定长度
     * @return
     */
    public String genCode(String randomStr,int length){
        String code = RandomUtil.randomNumber(length);
        verificationCodeDao.insertCode(randomStr,code);
        return code;
    }

    /**
     * 校验验证码
     * @return
     */
    public boolean checkCode(String randomStr,String code){
        String storeCode = verificationCodeDao.selectCode(randomStr);
        return code.equals(storeCode);
    }

    /**
     * 校验验证码返回不同标记
     * 0-正常
     * 1-超时
     * 2-不匹配
     * @return
     */
    public WpState checkCodeState(String randomStr, String code){
        String storeCode = verificationCodeDao.selectCode(randomStr);

        // 超时
        if(StrUtil.isBlank(storeCode)) {
            WpState state = new WpState();
            state.setCode(1);
            return state;
        }

        // 不匹配
        if(!storeCode.equals(code)){
            WpState state = new WpState();
            state.setCode(2);
            return state;
        }

        // 正常
        return new WpState();
    }
}
